<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
<script src="resources/common.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
description("Test deriving HKDF keys with deriveKey()");

jsTestIsAsync = true;

var derivingKeyAlgorithm = {
    name: "HKDF",
    hash: "SHA-256",
    salt: new Uint8Array(),
    info: new Uint8Array()
};

var privateKeyJSON = {
    "kty": "EC",
    "crv": "P-256",
    "d": "1mGcHOo_eTxXMTgSjWLLa5DCZIf0o8NNySooVNefCIw",
    "x": "QcD58SaUjtYiUaUnTaOMWC7YKyfQ5yD0-8F9RStayBU",
    "y": "CjHmp9BL54FleRbhJVQb1MgVu5YsFn7tJt0VWof_jj0"
};

var publicKeyJSON = {
    "kty": "EC",
    "crv": "P-256",
    "x": "AGzVMZDcNVrG7e8m9bLFTy7Si7o1IcU-SNyI8_Up62E",
    "y": "bSVna0fR_BTIgH5--cEXXgOB3J2IlxKTmb8YeOZ7UKE"
};

var secret = hexStringToUint8Array("82b17497eefdeee07fb108496b1e88b1975e42a98046b5521d18edc96a639fea");

var hkdfAlgorithm = {
    name: "HKDF",
    hash: "SHA-256",
    salt: new Uint8Array(),
    info: new Uint8Array()
}

Promise.resolve(null).then(function(result) {
    return crypto.subtle.importKey("jwk", privateKeyJSON, {name: "ECDH", namedCurve: "P-256"}, true, ["deriveKey"]);
}).then(function(result) {
    privateKey = result;

    return crypto.subtle.importKey("jwk", publicKeyJSON, {name: "ECDH", namedCurve: "P-256"}, true, []);
}).then(function(result) {
    publicKey = result;

    debug("Derive an HKDF key from ECDH keys");
    return crypto.subtle.deriveKey({name: "ECDH", namedCurve: "P-256", public: publicKey}, privateKey, "HKDF", false, ['deriveKey', 'deriveBits']);
}).then(function(result) {
    hkdfKey = result;

    shouldEvaluateAs("hkdfKey.algorithm.name", "HKDF");
    shouldEvaluateAs("hkdfKey.extractable", false);
    shouldEvaluateAs("hkdfKey.usages.join(',')", "deriveKey,deriveBits");

    debug("\nDerive 128 bits from the HKDF key");
    return crypto.subtle.deriveBits(hkdfAlgorithm, hkdfKey, 128);
}).then(function(result) {
    derivedBits = result;

    return crypto.subtle.importKey("raw", secret, hkdfAlgorithm, false, ['deriveBits']);
}).then(function(hkdfKey) {
    return crypto.subtle.deriveBits(hkdfAlgorithm, hkdfKey, 128);
}).then(function(result) {
    expectedDerivedBits = result;

    shouldEvaluateAs("bytesToHexString(derivedBits)", bytesToHexString(expectedDerivedBits));
}).then(finishJSTest, failAndFinishJSTest);

</script>

</body>
</html>
